﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Data.SqlClient;
using System.Data;
using System.Collections;

namespace IEWebSite.Administration
{
    public partial class Curs : BaseListPage
    {
        protected override string GetTableName()
        {
            return "Curs";
        }

        #region Properties
        protected CatedraIEDB.CursDataTable SessionTable
        {
            get
            {
                object obj = this.Session[GetTableName()];
                if ((!(obj == null)))
                {
                    return ((CatedraIEDB.CursDataTable)(obj));
                }
                CatedraIEDB.CursDataTable cursDataTable = new CatedraIEDB.CursDataTable();
                cursDataTable = cursTableAdaptor.GetData();
                this.Session[GetTableName()] = cursDataTable;
                return cursDataTable;
            }
        }
        #endregion

        #region Attributes
        CatedraIEDBTableAdapters.CursTableAdapter cursTableAdaptor;
        #endregion

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            cursTableAdaptor = new CatedraIEDBTableAdapters.CursTableAdapter();
 
            if (!Page.IsPostBack)
            {
                RadGrid1.DataSource = SessionTable;
                RadGrid1.DataBind();
            }
        }

        protected void RadGrid1_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

            CatedraIEDB.CursRow newRow = (CatedraIEDB.CursRow)this.SessionTable.NewRow();

            newRow.Titlu = (userControl.FindControl("txtTitlu") as TextBox).Text;
            newRow.Descriere = (userControl.FindControl("Descriere") as RadEditor).Text;
            newRow.TitluEN = (userControl.FindControl("txtTitluEN") as TextBox).Text;
            newRow.DescriereEN = (userControl.FindControl("DescriereEN") as RadEditor).Text;
            FileUpload fileUpload = (userControl.FindControl("FileUpload1") as FileUpload);
            if (fileUpload.FileBytes.Length != 0)
            {
                newRow.Fisier = fileUpload.FileBytes;
                newRow.FisierMimeType = (userControl.FindControl("FileUpload1") as FileUpload).PostedFile.ContentType;
            }
            newRow.IdCiclu = Int32.Parse((userControl.FindControl("ddlCiclu") as DropDownList).SelectedValue);
            newRow.IdPlanInvatamant = Int32.Parse((userControl.FindControl("ddlPlanInv") as DropDownList).SelectedValue);
            newRow.IdSysTipDisciplina = Int32.Parse((userControl.FindControl("ddlTipDisciplina") as DropDownList).SelectedValue);
            newRow.IdSysCategorieDisciplina = Int32.Parse((userControl.FindControl("ddlCategorie") as DropDownList).SelectedValue);
            newRow.AnStudiu = Int32.Parse((userControl.FindControl("ddlAnStudiu") as DropDownList).SelectedValue);
            newRow.Semestru = Int32.Parse((userControl.FindControl("ddlSemestru") as DropDownList).SelectedValue);
            newRow.NrC = Int32.Parse((userControl.FindControl("ddlC") as DropDownList).SelectedValue);
            newRow.NrS = Int32.Parse((userControl.FindControl("ddlS") as DropDownList).SelectedValue);
            newRow.NrLP = Int32.Parse((userControl.FindControl("ddlLP") as DropDownList).SelectedValue);
            newRow.PuncteCredit = Int32.Parse((userControl.FindControl("ddlNrPuncteCredit") as DropDownList).SelectedValue);

            newRow[GetKeyColumn()] = Utils.GetNextTableId(GetTableName());

            try{
                this.SessionTable.Rows.Add(newRow);
                cursTableAdaptor.Update((CatedraIEDB.CursDataTable)SessionTable);
                SessionTable.AcceptChanges();
            }
            catch (Exception ex)
            {
                Label lblError = new Label();
                lblError.Text = "Nu s-a putut realiza insertul. Motivul: " + ex.Message;
                lblError.ForeColor = System.Drawing.Color.Red;
                RadGrid1.Controls.Add(lblError);
                e.Canceled = true;
            }
        }

        protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            this.RadGrid1.DataSource = this.SessionTable;
        }

        protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
        {
            GridEditableItem editedItem = e.Item as GridEditableItem;
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
            CatedraIEDB.CursRow[] changedRows = (CatedraIEDB.CursRow[])this.SessionTable.Select(GetKeyColumn() + "= " + editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex][GetKeyColumn()]);
        
            if (changedRows.Length != 1)
            {
                RadGrid1.Controls.Add(new LiteralControl("Nu poate fi localizat cursul pentru a fi modificat."));
                e.Canceled = true;
                return;
            }

            Hashtable newValues = new Hashtable();
            newValues["Titlu"] = (userControl.FindControl("txtTitlu") as TextBox).Text;
            newValues["Descriere"] = (userControl.FindControl("Descriere") as RadEditor).Content;
            newValues["TitluEN"] = (userControl.FindControl("txtTitluEN") as TextBox).Text;
            newValues["DescriereEN"] = (userControl.FindControl("DescriereEN") as RadEditor).Content;

            FileUpload fileUpload = (userControl.FindControl("FileUpload1") as FileUpload);
            if (fileUpload.FileBytes.Length != 0)
            {
                changedRows[0].Fisier = fileUpload.FileBytes;
                //http://www.telerik.com/community/code-library/aspnet-ajax/general/radupload-in-ajax-enabled-radgrid.aspx
                changedRows[0].FisierMimeType = (userControl.FindControl("FileUpload1") as FileUpload).PostedFile.ContentType;
                // Find number of bytes in stream.
                //Int32 strLen = Convert.ToInt32(str.Length);
                // Create a byte array.
                //byte[] strArr = new byte[strLen];
                // Read stream into byte array.
                //str.Read(strArr, 0, strLen);
                //changedRows[0].Pdf = strArr;
            }
            newValues["IdCiclu"] = Int32.Parse((userControl.FindControl("ddlCiclu") as DropDownList).SelectedValue);
            newValues["IdPlanInvatamant"] = Int32.Parse((userControl.FindControl("ddlPlanInv") as DropDownList).SelectedValue);
            newValues["IdSysTipDisciplina"] = Int32.Parse((userControl.FindControl("ddlTipDisciplina") as DropDownList).SelectedValue);
            newValues["IdSysCategorieDisciplina"] = Int32.Parse((userControl.FindControl("ddlCategorie") as DropDownList).SelectedValue);
            newValues["AnStudiu"] = Int32.Parse((userControl.FindControl("ddlAnStudiu") as DropDownList).SelectedValue);
            newValues["Semestru"] = Int32.Parse((userControl.FindControl("ddlSemestru") as DropDownList).SelectedValue);
            newValues["NrC"] = Int32.Parse((userControl.FindControl("ddlC") as DropDownList).SelectedValue);
            newValues["NrS"] = Int32.Parse((userControl.FindControl("ddlS") as DropDownList).SelectedValue);
            newValues["NrLP"] = Int32.Parse((userControl.FindControl("ddlLP") as DropDownList).SelectedValue);
            newValues["PuncteCredit"] = Int32.Parse((userControl.FindControl("ddlNrPuncteCredit") as DropDownList).SelectedValue);

            changedRows[0].BeginEdit();
            try
            {
                foreach (DictionaryEntry entry in newValues)
                {
                    changedRows[0][(string)entry.Key] = entry.Value;
                }
                changedRows[0].EndEdit();
                cursTableAdaptor.Update((CatedraIEDB.CursDataTable)SessionTable);
                SessionTable.AcceptChanges();
            }
            catch (Exception ex)
            {
                changedRows[0].CancelEdit();

                Label lblError = new Label();
                lblError.Text = "Nu s-a putut realiza Upate-ul. Motivul: " + ex.Message;
                lblError.ForeColor = System.Drawing.Color.Red;
                RadGrid1.Controls.Add(lblError);

                e.Canceled = true;
            }
        }

        protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
        {
            string ID = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex][GetKeyColumn()].ToString();
            if (SessionTable.Rows.Find(ID) != null)
            {
                SessionTable.Rows.Find(ID).Delete();
                cursTableAdaptor.Update((CatedraIEDB.CursDataTable)SessionTable);
                SessionTable.AcceptChanges();
            }
        }

       /// <summary>
       /// Remove, Add, Customize Columns
       /// http://www.telerik.com/help/aspnet/grid/grdusingcolumns.html
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
        protected void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
        {
            //Remove Id Column
            if (e.Column.UniqueName.StartsWith("Id") || e.Column.UniqueName == "FisierMimeType")
            {
                GridBoundColumn boundColumn = e.Column as GridBoundColumn;
                boundColumn.Visible = false;
            }
            else if (e.Column.UniqueName == "Link")
            {
                GridBoundColumn boundColumn = e.Column as GridBoundColumn;
                boundColumn.DataField = GetKeyColumn();
                boundColumn.DataFormatString = "<a href=\"DBFileDownloader.aspx?table=Curs&column=Fisier&id={0:D}\" target=\"_blank\">Descarcă</a>";
            }
        }
        #endregion

       
    }
}
